package com.hctforgreen.greenservice.utils;

import android.text.TextUtils;
import android.util.Log;

import com.hctforgreen.greenservice.HomeRepairInstallActivity;
import com.hctforgreen.greenservice.model.AppRoleEntity;
import com.hctforgreen.greenservice.model.StaffRoleEntity;
import com.hctforgreen.greenservice.model.UserIdentityEntity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Author:liuyanguo
 * Date:2017/12/27
 * Time:9:09
 * Description:Okhttp的网络访问类
 */

public class HttpUtil {
    private static final String TAG = "HttpUtil";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static HttpUtil sInstance = null;

    private HttpUtil() {
    }

    public static HttpUtil getInstance() {
        if (null == sInstance) {
            synchronized (HttpUtil.class) {
                if (null == sInstance) {
                    sInstance = new HttpUtil();
                }
            }
        }
        return sInstance;
    }

    private OkHttpClient sClient = null;
    private Request mGetUserTypeRequest;

    /**
     * 用Map提交电话号码去获取到用户的身份
     *
     * @param url
     * @param data
     * @return
     */
    public String postUserIdByPhone(String url, Map<String, String> data) {
        LogUtil.d(TAG, "开始进行post操作...");
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : data.keySet()) {
            //追加表单信息
            builder.add(key, data.get(key));
        }
        //生成表单实体对象
        RequestBody formBody = builder.build();
        LogUtil.d(TAG, "表单构建成功...");
        mGetUserTypeRequest = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        LogUtil.d(TAG, "准备执行请求...");
        Response response = execute(mGetUserTypeRequest);
        LogUtil.d(TAG, "请求提交成功...");
        if (null != response && response.isSuccessful()) {
            String respString = null;
            try {
                respString = response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
            LogUtil.d(TAG, respString);
            return respString;
        }
        return null;
    }

    /**
     * 用Json进行post请求
     *
     * @param url
     * @param postString
     * @param tag
     * @return
     */
    public String postParamsByJson(String url, String postString, String tag) {
        LogUtil.d(TAG, "url = " + url);
        LogUtil.d(TAG, "params = " + postString);
        RequestBody requestBody = RequestBody.create(JSON, postString);
        mGetUserTypeRequest = new Request.Builder()
                .url(url)
                .post(requestBody)
                .tag(tag)
                .build();
        try {
            Response response = execute(mGetUserTypeRequest);
            if (null != response && response.isSuccessful()) {
                String respString = response.body().string();
                LogUtil.d(TAG, "respString = " + respString);
                return respString;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getAppRoleByPhone(String url, Map<String, String> params, String tag) {
        LogUtil.d(TAG, "url = " + url);
        StringBuilder builder = new StringBuilder();
        for (String key : params.keySet()) {
            builder.append(key);
            builder.append("=");
            builder.append(params.get(key));
            builder.append("&");
        }
        String requesetUrl = url + "?" + builder.toString().substring(0, builder.length() - 1);
        LogUtil.d(TAG, "requestUrl = " + requesetUrl);
        mGetUserTypeRequest = new Request.Builder()
                .url(requesetUrl)
                .get()
                .tag(tag)
                .build();
        try {
            Response response = execute(mGetUserTypeRequest);
            if (null != response && response.isSuccessful()) {
                String respString = response.body().string();
                LogUtil.d(TAG, "respString = " + respString);
                return respString;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析获取到的staffType的json数据
     *
     * @param jsonString
     * @return
     */
    public StaffRoleEntity parseStaffRole(String jsonString) {
        StaffRoleEntity entity = null;
        if (TextUtils.isEmpty(jsonString)) {
            return entity;
        }
        try {
            entity = new StaffRoleEntity();
            JSONObject root = new JSONObject(jsonString);
            int errorCode = root.getInt("errorCode");
            entity.setErrorCode(errorCode);
            String staffWorkType = root.getString("staffWorkType");
            entity.setStaffWorkType(staffWorkType);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return entity;
    }

    /**
     * 通过json字符串解析出实体类
     *
     * @param jsonString
     * @return
     */
    public UserIdentityEntity getBeanByParseJson(String jsonString) {
        UserIdentityEntity entity = null;
        try {
            JSONObject root = new JSONObject(jsonString);
            String staffWorkType = root.getString("staffWorkType");
            int errorCode = root.getInt("errorCode");
            entity.setStaffWorkType(staffWorkType);
            entity.setErrorCode(errorCode);
        } catch (JSONException e) {
            LogUtil.d(TAG, "数据解析出错...");
            e.printStackTrace();
        }
        return entity;
    }

    /**
     * get请求
     *
     * @param url
     * @return
     */
    public String get(String url) {
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        LogUtil.d(TAG, "准备执行请求...");
        try {
            Response response = execute(request);
            if (null != response && response.isSuccessful()) {
                String respString = response.body().string();
                LogUtil.d(TAG, "respString = " + respString);
                return respString;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析出AppRole
     *
     * @param jsonString
     * @return
     */
    public AppRoleEntity parse(String jsonString) {
        AppRoleEntity entity = null;
        if (TextUtils.isEmpty(jsonString)) {
            Log.e(TAG, "JsonString can not be null.");
            return entity;
        }
        try {
            JSONObject root = new JSONObject(jsonString);
            String appRole = root.getString("name");
            entity = new AppRoleEntity();
            entity.setAppRole(appRole);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return entity;
    }

    /**
     * 请求
     *
     * @param request
     * @return
     */
    public Response execute(Request request) {
        sClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        try {
            return sClient.newCall(request).execute();
        } catch (IOException e) {
            if (sClient.newCall(request).isCanceled()) {
                e.printStackTrace();
            } else {
                if (null != HomeRepairInstallActivity.sHandler) {
                    HomeRepairInstallActivity.sHandler.sendMessage(
                            HomeRepairInstallActivity.sHandler.obtainMessage(1));
                }
            }
        }
        return null;
    }

    /**
     * 取消Request的执行
     */
    public void cancelGetUserTypeRequest() {
        if (null != sClient) {
            sClient.dispatcher().cancelAll();
        }
    }
}
